package com.github.catvod.spider;

import android.content.Context;
import com.github.catvod.crawler.Spider;
import com.github.catvod.net.SSLSocketFactoryCompat;
import com.github.catvod.utils.Util;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhixc
 * 哔哩兔
 */
public class WenYou7 extends Spider {

//    private final String siteUrl = "http://192.168.100.153:9997/tv/f55/";

    private String siteUrl;


    /**
     * 爬虫代码初始化
     *
     * @param context 上下文对象
     * @param extend  配置文件的 ext 参数
     */
    @Override
    public void init(Context context, String extend) {
        super.init(context, extend);
        // 域名经常性发生变化，通过外部配置文件传入，可以方便修改
        if (extend.endsWith("/")) {
            extend = extend.substring(0, extend.lastIndexOf("/"));
        }
        siteUrl = extend;
    }

    /**
     * 首页内容
     */
    @Override
    public String homeContent(boolean filter) {
        try {
            String content = getWebContent(siteUrl + "/homeContent");
            return content;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 分类页面
     *
     * @param tid    影片分类id值
     * @param pg     第几页
     * @param extend 筛选
     * @return 返回 json 字符串
     */
    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) {
        try {
            String cateUrl = String.format(siteUrl + "/categoryContent?tid=%s&pg=%s", tid, pg);
            String content = getWebContent(cateUrl);
            return content;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private String getWebContent(String targetUrl) throws IOException {
        String ip = Util.getRandomIp();
        String ua = Util.getRandomUserAgent();
        Request request = new Request.Builder()
                .url(targetUrl)
                .get()
                //.addHeader("User-Agent", ua)
                //.addHeader("Host", "55dy1.vip")
                //.addHeader("x-forwarded-for", ip)
                .build();


        OkHttpClient okHttpClient = new OkHttpClient()
                .newBuilder()
                .readTimeout(50, TimeUnit.SECONDS)
                .callTimeout(50, TimeUnit.SECONDS)
                //.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.9.149", 10811)))
                .sslSocketFactory(new SSLSocketFactoryCompat(), SSLSocketFactoryCompat.trustAllCert)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if (response.body() == null) return "";
        String content = response.body().string();
        response.close();
        return content;
    }

    /**
     * 详情页
     */
    @Override
    public String detailContent(List<String> ids) {
        try {
            String content = getWebContent(siteUrl + "/detailContent?id=" + ids.get(0));
            return content;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 搜索
     *
     * @param key 关键字/词
     */
    @Override
    public String searchContent(String key, boolean quick) {
        try {
            String searchUrl = String.format(siteUrl + "/searchContent?key=%s", key);
            String searchResult = getWebContent(searchUrl);
            return searchResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public String playerContent(String flag, String playUrl, List<String> vipFlags) {
        try {
            String contentUrl = String.format(siteUrl + "/playerContent?flag=%s&playUrl=%s", flag,playUrl);
            String content = getWebContent(contentUrl);
            return content;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    private HashMap<String, String> getHeaders(String url) {
        String ip = Util.getRandomIp();
        String ua = Util.getRandomUserAgent();
        HashMap<String, String> headers = new HashMap<>();
        //headers.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36");
        headers.put("User-Agent", ua);
        //headers.put("Host", "55dy1.vip");
        headers.put("x-forwarded-for", ip);
        return headers;
    }
}
